package com.g13.virtualpethospital.controller;

import com.g13.virtualpethospital.common.EntityCommon;
import com.g13.virtualpethospital.common.Result;
import com.g13.virtualpethospital.controller.request.CaseInfoRequest;
import com.g13.virtualpethospital.controller.request.CaseRequest;
import com.g13.virtualpethospital.controller.request.CaseUploadRequest;
import com.g13.virtualpethospital.controller.request.QuestionRequest;
import com.g13.virtualpethospital.entity.CaseEntity;
import com.g13.virtualpethospital.entity.QuestionEntity;
import com.g13.virtualpethospital.entity.base.CaseSession;
import com.g13.virtualpethospital.entity.base.MultMedia;
import com.g13.virtualpethospital.service.CaseService;
import com.g13.virtualpethospital.service.MultMediaService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@ApiModel("病例操作相关接口")
@RequestMapping("/case")
public class CaseController {
    @Autowired
    private CaseService caseService;
    @Autowired
    private MultMediaService mediaService;

    @GetMapping("/back-getAllCase")
    @ApiOperation("查询所有病例")
    @ResponseBody
    public Result<List<CaseEntity>> getAllCase() {
        List<CaseEntity> allCase = caseService.findAllCase();
        return Result.success(allCase);
    }

    @GetMapping("/back-getCaseByCatalog")
    @ApiOperation("按分类查找病例")
    @ResponseBody
    public Result<List<CaseEntity>> getCaseByCatalog(@RequestParam("menu") String menu, @RequestParam("subMenu") String subMenu) {
        List<CaseEntity> cases = caseService.findCaseByType(menu, subMenu);
        if (cases != null) {
            return Result.success(cases);
        }
        return Result.fail("无该分类病例");
    }

    @GetMapping("/back-getCaseByKey")
    @ApiOperation("按关键字查找病例")
    @ResponseBody
    public Result<List<CaseEntity>> getCaseByCatalog(@RequestParam("caseKey") String caseKey) {
        List<CaseEntity> cases = caseService.findCaseByName(caseKey);
        if (cases != null) {
            return Result.success(cases);
        }
        return Result.fail("无该关键字病例");
    }

    @GetMapping("/back-getInfo")
    @ApiOperation("查看病例信息")
    @ResponseBody
    public Result<CaseSession> getInfo(@RequestParam("caseId") String caseId, @RequestParam("module") String module) {
        List<CaseEntity> cases = caseService.findCaseById(caseId);
        CaseEntity entity = cases.get(0);
        CaseSession result = null;
        if ("caseCheck".equals(module)) {
            result = entity.getCaseCheck();
        } else if ("caseDiag".equals(module)) {
            result = entity.getCaseDiag();
        } else if ("caseTake".equals(module)) {
            result = entity.getCaseTake();
        } else if ("caseTherapy".equals(module)) {
            result = entity.getCaseTherapy();
        }
        if (result != null) {
            return Result.success(result);
        }
        return Result.fail("无该病例");
    }

    @PostMapping("/addCase")
    @ApiOperation("新增病例")
    @ResponseBody
    public Result<Integer> addCase(@RequestBody CaseRequest caseRequest) {
        try {
            if (caseRequest == null || caseRequest.getCaseName() == null || caseRequest.getMenu() == null || caseRequest.getSubMenu() == null) {
                return Result.fail("参数不能为空");
            } else {
                CaseEntity entity = new CaseEntity();
                entity.setCaseName(caseRequest.getCaseName());
                entity.setMenu(caseRequest.getMenu());
                entity.setSubMenu(caseRequest.getSubMenu());
                caseService.addCase(entity);
                return Result.success("添加成功", null);
            }
        } catch (Exception e) {
            return Result.fail("添加失败");
        }
    }

    @PutMapping("/modifyCase")
    @ApiOperation("修改病例名称")
    @ResponseBody
    public Result<CaseEntity> modifyCase(@RequestBody CaseRequest caseRequest) {
        try {
            if (caseRequest == null || caseRequest.getCaseId() == null || caseRequest.getCaseName() == null || caseRequest.getMenu() == null || caseRequest.getSubMenu() == null) {
                return Result.fail("参数不能为空");
            }
            CaseEntity entity = new CaseEntity();
            entity.setCaseId(caseRequest.getCaseId());
            entity.setCaseName(caseRequest.getCaseName());
            entity.setMenu(caseRequest.getMenu());
            entity.setSubMenu(caseRequest.getSubMenu());
            caseService.updateCase(entity, entity.getCaseId());
            return Result.success("修改成功", entity);
        } catch (Exception e) {
            return Result.fail("修改失败");
        }
    }

    @DeleteMapping("/deleteCase")
    @ApiOperation("删除病例")
    @ResponseBody
    public Result<Integer> deleteCase(@NonNull @RequestParam("caseId") String caseId) {
        try {
            caseService.deleteCase(caseId);
            return Result.success("删除成功", null);
        } catch (Exception e) {
            return Result.fail("删除失败");
        }
    }

    //上传病例信息
    @PostMapping("/uploadInfo")
    @ApiOperation("上传病例信息(覆盖)")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "caseId", value = "病例ID", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "module", value = "模块名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type",value = "素材种类(pic video or describe)", required = true,paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "file", value = "文件（如果存在）", required = false, paramType = "query",dataType = "file"),
            @ApiImplicitParam(name = "describe", value = "描述（如果存在）", required = false, paramType = "query", dataType = "String")
    })
    public Result<Integer> uploadInfo(@NonNull @RequestParam("caseId") String caseId, @NonNull @RequestParam("module") String module,
                                      @NonNull @RequestParam("type") String type, @RequestParam("file") MultipartFile[] file,
                                      @RequestParam("describe") String describe) {
        return updateInfo(caseId, module, type, file, describe);
    }

    //修改病例信息
    @PostMapping("/updateInfo")
    @ApiOperation("修改病例信息(覆盖)")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "caseId", value = "病例ID", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "module", value = "模块名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type",value = "素材种类(pic video or describe)", required = true,paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "file", value = "文件（如果存在）", required = false, paramType = "query",dataType = "file"),
            @ApiImplicitParam(name = "describe", value = "描述（如果存在）", required = false, paramType = "query", dataType = "String")
    })
    public Result<Integer> updateInfo(@NonNull @RequestParam("caseId") String caseId, @NonNull @RequestParam("module") String module,
                                      @NonNull @RequestParam("type") String type, @RequestParam("file") MultipartFile[] file,
                                      @RequestParam("describe") String describe) {
//        try {
//            if (caseInfo == null || caseInfo.getCaseId() == null || caseInfo.getModule() == null || caseInfo.getType() == null) {
//                return Result.fail("参数不能为空");
//            }

//            String module = caseInfo.getModule();
//            CaseEntity caseEntity = new CaseEntity();
//            caseEntity.setCaseId(caseInfo.getCaseId());
//            CaseSession caseSession = new CaseSession();
//
//            MultMedia multMedia = null;
//            List<MultMedia> updateList = new ArrayList<>();
//
//            if ("video".equals(caseInfo.getType())) {
//                for (MultipartFile multipartFile : file) {
//                    multMedia = mediaService.addResource(multipartFile, EntityCommon.MultiMediaType.VIDEO);
//                    updateList.add(multMedia);
//                }
//                caseSession.setVideo(updateList);
//            } else if ("pic".equals(caseInfo.getType())) {
//                for (MultipartFile multipartFile : file) {
//                    multMedia = mediaService.addResource(multipartFile, EntityCommon.MultiMediaType.PIC);
//                    updateList.add(multMedia);
//                }
//                caseSession.setPic(updateList);
//            } else if ("describe".equals(caseInfo.getType())) {
//                caseSession.setDescribe(caseInfo.);
//            }
//
//            if ("caseCheck".equals(module)) {
//                caseEntity.setCaseCheck(caseSession);
//            } else if ("caseDiag".equals(module)) {
//                caseEntity.setCaseDiag(caseSession);
//            } else if ("caseTake".equals(module)) {
//                caseEntity.setCaseTake(caseSession);
//            } else if ("caseTherapy".equals(module)) {
//                caseEntity.setCaseTherapy(caseSession);
//            }
//            caseService.updateCase(caseEntity, caseEntity.getCaseId());
//            return Result.success("修改成功", null);
//        } catch (Exception e) {
//            return Result.fail("修改失败");
//        }
       try{
           CaseEntity caseEntity = new CaseEntity(), originCase = null;
           CaseSession caseSession = new CaseSession();
           List<MultMedia> multMediaList = new ArrayList<>();

           // check the caseId is existed.
           List<CaseEntity> caseEntityList = caseService.findCaseById(caseId);
           if(caseEntityList.isEmpty()) return Result.fail("找不到用例");
           else originCase = caseEntityList.get(0);

           if(type.equals("pic")){
               for(MultipartFile multipartFile: file){
                   multMediaList.add(mediaService.addResource(multipartFile, EntityCommon.MultiMediaType.PIC));
               }
               caseSession.setPic(multMediaList);
               if(module.equals("caseCheck")){
                   if(originCase.getCaseCheck() != null) {
                       caseSession.setDescribe(originCase.getCaseCheck().getDescribe());
                       caseSession.setVideo(originCase.getCaseCheck().getVideo());
                   }
                   caseEntity.setCaseCheck(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseDiag")) {
                   if (originCase.getCaseDiag() != null){
                       caseSession.setDescribe(originCase.getCaseDiag().getDescribe());
                       caseSession.setVideo(originCase.getCaseDiag().getVideo());
                   }
                   caseEntity.setCaseDiag(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseTake")) {
                   if(originCase.getCaseTake() != null){
                       caseSession.setDescribe(originCase.getCaseTake().getDescribe());
                       caseSession.setVideo(originCase.getCaseTake().getVideo());
                   }
                   caseEntity.setCaseTake(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseTherapy")) {
                   if (originCase.getCaseTherapy() != null){
                       caseSession.setDescribe(originCase.getCaseTherapy().getDescribe());
                       caseSession.setVideo(originCase.getCaseTherapy().getVideo());
                   }
                   caseEntity.setCaseTherapy(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               }else {
                   return Result.fail("模块错误");
               }

           } else if (type.equals("video")) {
               for (MultipartFile multipartFile: file){
                   multMediaList.add(mediaService.addResource(multipartFile, EntityCommon.MultiMediaType.VIDEO));
               }
               caseSession.setVideo(multMediaList);
               if(module.equals("caseCheck")){
                   if (originCase.getCaseCheck() != null){
                       caseSession.setDescribe(originCase.getCaseCheck().getDescribe());
                       caseSession.setPic(originCase.getCaseCheck().getPic());
                   }
                   caseEntity.setCaseCheck(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseDiag")) {
                   if(originCase.getCaseDiag() != null){
                       caseSession.setDescribe(originCase.getCaseDiag().getDescribe());
                       caseSession.setPic(originCase.getCaseDiag().getPic());
                   }
                   caseEntity.setCaseDiag(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseTake")) {
                   if(originCase.getCaseTake() != null){
                       caseSession.setDescribe(originCase.getCaseTake().getDescribe());
                       caseSession.setPic(originCase.getCaseTake().getPic());
                   }
                   caseEntity.setCaseTake(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseTherapy")) {
                   if(originCase.getCaseTherapy() != null){
                       caseSession.setDescribe(originCase.getCaseTherapy().getDescribe());
                       caseSession.setPic(originCase.getCaseTherapy().getPic());
                   }
                   caseEntity.setCaseTherapy(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               }else {
                   return Result.fail("模块错误");
               }
           }
           else if (type.equals("describe")){
               caseSession.setDescribe(describe);
               if(module.equals("caseCheck")){
                   if(originCase.getCaseCheck() != null){
                       caseSession.setVideo(originCase.getCaseCheck().getVideo());
                       caseSession.setPic(originCase.getCaseCheck().getPic());
                   }
                   caseEntity.setCaseCheck(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseDiag")) {
                   if (originCase.getCaseDiag() != null){
                       caseSession.setVideo(originCase.getCaseDiag().getVideo());
                       caseSession.setPic(originCase.getCaseDiag().getPic());
                   }
                   caseEntity.setCaseDiag(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseTake")) {
                   if (originCase.getCaseTake() != null){
                       caseSession.setVideo(originCase.getCaseTake().getVideo());
                       caseSession.setPic(originCase.getCaseTake().getPic());
                   }
                   caseEntity.setCaseTake(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               } else if (module.equals("caseTherapy")) {
                   if (originCase.getCaseTherapy() != null){
                       caseSession.setVideo(originCase.getCaseTherapy().getVideo());
                       caseSession.setPic(originCase.getCaseTherapy().getPic());
                   }
                   caseEntity.setCaseTherapy(caseSession);
                   caseService.updateCase(caseEntity, caseId);
                   return Result.success("修改成功", null);
               }else {
                   return Result.fail("模块错误");
               }
           }
           else {
               return Result.fail("错误的素材类型");
           }
       }catch (Exception e){
           return Result.fail("更新失败");
       }
    }


    @DeleteMapping("/deleteInfo")
    @ApiOperation("删除病例信息")
    @ResponseBody
    public Result<Integer> deleteInfo(@RequestBody CaseInfoRequest caseInfo) {
        try {
            String module = caseInfo.getModule();
            CaseEntity caseEntity = new CaseEntity();
            caseEntity.setCaseId(caseInfo.getCaseId());
            if ("caseCheck".equals(module)) {
                caseEntity.setCaseCheck(null);
            } else if ("caseDiag".equals(module)) {
                caseEntity.setCaseDiag(null);
            } else if ("caseTake".equals(module)) {
                caseEntity.setCaseTake(null);
            } else if ("caseTherapy".equals(module)) {
                caseEntity.setCaseTherapy(null);
            }
            if ("pic".equals(caseInfo.getType())) {
                mediaService.deleteResource(caseInfo.getName(), EntityCommon.MultiMediaType.PIC);
            }
            if ("video".equals(caseInfo.getType())) {
                mediaService.deleteResource(caseInfo.getName(), EntityCommon.MultiMediaType.VIDEO);
            }
            caseService.updateCase(caseEntity, caseEntity.getCaseId());
            return Result.success("删除成功", null);
        } catch (Exception e) {
            return Result.fail("删除失败");
        }
    }


}
